// 临时帮助运维维护设备的指令
package robot

import (
	"context"
	"device-admin/internal/app/grpc/service/terminal"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"math/rand"
	"time"

	"192.168.1.75/go-pkg/logx"
	"github.com/samber/lo"
)

// InitADBEnv 初始化95环境
// 安装adb
// 杀死旧的adb进程
// 启动adb服务
// 修改teleport工作目录的所属用户组
func InitADBEnv(robotID string) {
	time.AfterFunc(time.Second*10, func() { // 延迟执行是为了确保teleport链接成功
		terminal.SendShellCMDTo95(robotID, []string{
			"echo dadaozhichuang | sudo -S apt-get update",
			"echo dadaozhichuang | sudo -S apt-get install android-tools-adb",
			"echo dadaozhichuang | sudo -S bash -c 'pgrep adbd | xargs kill -9'",
			"echo dadaozhichuang | sudo -S adb start-server",
			"echo dadaozhichuang | sudo -S chown dadao:dadao /home/dadao/DDR_Linux/teleport",
		}, 30)
	})
}

// AutoUpdateDevice95Arch 自动更新95的cpu架构信息
// 每次连接成功后检查一次
func AutoUpdateDevice95Arch(robotID string) {
	time.AfterFunc(time.Second*10, func() {
		rd := rand.New(rand.NewSource(time.Now().UnixNano()))
		time.Sleep(time.Second * time.Duration(rd.Intn(30)))
		td, _ := dao.Terminal{}.Detail(context.Background(), dal.Q, robotID, "95")
		if td != nil && td.Arch == 0 {
			res, err := terminal.SendShellCMDAndRecvRes(robotID, "uname -m", 5)
			logx.Info(context.Background(), "auto update cpu arch", logx.String("res", res), logx.Err(err))
			if res != "" {
				if res == "x86_64" {
					dao.Terminal{}.UpdateArch(context.Background(), dal.Q, robotID, "95", 1)
				} else if res == "aarch64" || res == "arm64" {
					dao.Terminal{}.UpdateArch(context.Background(), dal.Q, robotID, "95", 2)
				}
			}
		}
	})
}

// TaskReordSchedule 任务记录上报调度
func TaskReordSchedule(robotID string) {
	if time.Now().Year() == 2024 && int(time.Now().Month()) == 3 && time.Now().Day() == 14 {
		time.AfterFunc(time.Minute, func() {
			if lo.Contains([]string{"DDRetail356", "DDRetail312", "DDRetail254", "DDRetail292", "DDRetail383", "DDRetail276", "DDRetail542"}, robotID) {
				terminal.SendShellCMDTo95(robotID, []string{
					"cd /home/dadao/DDR_Linux/Server/UserData",
					"mkdir TaskRecordInfo.bak",
					"mv TaskRecordInfo/* TaskRecordInfo.bak/",
					"mkdir TaskRecordInfo.expire",
					"find ./TaskRecordInfo.bak -type f -mtime +3 -exec mv {} TaskRecordInfo.expire/ \\;",
				}, 10)
			} else {
				terminal.SendShellCMDTo95(robotID, []string{
					"cd /home/dadao/DDR_Linux/Server/UserData",
					"mkdir TaskRecordInfo.bak",
					"mv TaskRecordInfo/* TaskRecordInfo.bak/",
					"mkdir TaskRecordInfo.expire",
					"find ./TaskRecordInfo.bak -type f -mtime +1 -exec mv {} TaskRecordInfo.expire/ \\;",
				}, 10)
			}
		})
	}
}
